package com.cd2cd.code_template.util.japidoc;

import io.github.yedaxia.apidocs.I18n;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取jApiDoc模板
 */
public class JApiTempUtil {

    public static String fetchResourceByFilePath(String path) throws IOException {
        InputStream in = JApiTempUtil.class.getResourceAsStream(path);

        String ss = IOUtils.toString(in, "utf-8");

        return ss;
    }

    private static Map<Integer, String> genMapByArray(Integer[] ignores) {
        Map<Integer, String> ignoreLine = new HashMap<>();
        for (int i = 0; i < ignores.length; i++) {
            ignoreLine.put(ignores[i], "-");
        }
        return ignoreLine;
    }

    /**
     * api-index.html ftl
     *
     * @param projectName
     * @return
     * @throws IOException
     */
    public static String getApiIndexFile(String projectName, boolean auto) throws IOException {
        String ss = fetchResourceByFilePath("/api-index.html.ftl");
        String[] lines = ss.split("\n");

        /**
         * jar api-index.html.ftl
         * <li class="dropdown">
         *   <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">${currentApiVersion}<span class="caret"></span></a>
         *   <ul class="dropdown-menu">
         *       <#list apiVersionList as version>
         *           <#if version != currentApiVersion>
         *               <li><a href="../${version}/index.html">${version}</a></li>
         *           </#if>
         *       </#list>
         *   </ul>
         * </li>
         */
        Integer[] ignoreArr = new Integer[]{23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
                56, 57, // <#list controllerNodeList as ctrolNode>
                73, 74, 75, 76 // <#list controllerNodeList as ctrolNode>
        };
        Map<Integer, String> ignoreLine = genMapByArray(ignoreArr);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {

            if (ignoreLine.containsKey(i + 1)) {
                continue;
            }

            /**
             * <#include "api-common-catalog.html.ftl"/>
             */
            if (i == 38) {
                // add catalog file
                sb.append(getApiCommonCatalogFile(1, auto) + "\n");
                continue;
            }

            if (i == 54) {
                sb.append("\t\t\t\t\t\t<!--ctrolNode-auto-start--> <!--ctrolNode-auto-end-->\n");
                sb.append("\t\t\t\t\t\t<!--ctrolNode-custom-start--> <!--ctrolNode-custom-end-->\n");
                continue;
            }

            if (i == 71) {
                sb.append("\t//--ctrolNode-auto-start \n\t//--ctrolNode-auto-end\n");
                sb.append("\t//--ctrolNode-custom-start \n\t//--ctrolNode-custom-end\n");
                continue;
            }
            sb.append(lines[i] + "\n");
        }

        // replace
        String res = sb.toString();


        I18n i18n = new I18n();
        String catalog = i18n.getMessage("catalog");
        String docGenerateTip = i18n.getMessage("doc.generate.tip");

        res = res.replaceAll("\\$\\{projectName\\}", projectName)
                .replaceAll("\\$\\{i18n.getMessage\\('catalog'\\)\\}", catalog)
                .replaceAll("\\$\\{i18n.getMessage\\('doc.generate.tip'\\)\\}", docGenerateTip);

        return res;
    }

    /**
     * api-controller ftl
     *
     * @param projectName
     * @param controllerName
     * @return
     * @throws IOException
     */
    public static String getApiControllerFile(String projectName, String controllerName, boolean auto) throws IOException {
        String ss = fetchResourceByFilePath("/api-controller.html.ftl");
        String[] lines = ss.split("\n");

        Integer[] ignoreArr = new Integer[]{23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
                56, 57, // <#list controllerNodeList as ctrolNode>
                53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
                89, 90, 91, 92
        };
        Map<Integer, String> ignoreLine = genMapByArray(ignoreArr);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {

            if (ignoreLine.containsKey(i + 1)) {
                continue;
            }

            if (i == 38) {
                // add catalog file
                sb.append(getApiCommonCatalogFile(1, auto) + "\n");
                continue;
            }

            if (i == 51) {
                sb.append("\t\t\t\t\t\t<!--ctrolNode-auto-start--> <!--ctrolNode-auto-end-->\n");
                sb.append("\t\t\t\t\t\t<!--ctrolNode-custom-start--> <!--ctrolNode-custom-end-->\n");
                continue;
            }

            if (i == 87) {
                sb.append("\t//--ctrolNode-auto-start \n\t//--ctrolNode-auto-end\n");
                sb.append("\t//--ctrolNode-custom-start \n\t//--ctrolNode-custom-end\n");
                continue;
            }

            sb.append(lines[i] + "\n");
        }

        // replace
        String res = sb.toString();


        I18n i18n = new I18n();
        String catalog = i18n.getMessage("catalog");
        String docGenerateTip = i18n.getMessage("doc.generate.tip");

        res = res.replaceAll("\\$\\{projectName\\}", projectName)
                .replaceAll("\\$\\{i18n.getMessage\\('catalog'\\)\\}", catalog)
                .replaceAll("\\$\\{i18n.getMessage\\('doc.generate.tip'\\)\\}", docGenerateTip)
                .replaceAll("\\$\\{controller.description\\}", controllerName);

        return res;
    }

    /**
     * api-common-catalog ftl
     *
     * @param type 1为静态内容，2为freemarker模板
     * @return
     * @throws IOException
     */
    public static String getApiCommonCatalogFile(int type, boolean auto) throws IOException {
        String ss = fetchResourceByFilePath("/api-common-catalog.html.ftl");

        String[] lines = ss.split("\n");

        Integer[] ignoreArr = null;
        if (type == 1) {
            ignoreArr = new Integer[]{
                    6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
            };
        } else {
            ignoreArr = new Integer[]{
                    1, 2, 3, 4, 5, 26
            };
        }
        Map<Integer, String> ignoreLine = genMapByArray(ignoreArr);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {

            if (ignoreLine.containsKey(i + 1)) {
                continue;
            }

            if (type == 1) {
                if (i == 12) {
                    sb.append("\t<!--catalog-auto-start--> <!--catalog-auto-end-->\n");
                    sb.append("\t<!--catalog-custom-start--> <!--catalog-custom-end-->\n");
                    continue;
                }

            }
            sb.append(lines[i] + "\n");
        }

        I18n i18n = new I18n();
        String searchPlaceholder = i18n.getMessage("searchPlaceholder");
        String newStr = i18n.getMessage("new");
        String modify = i18n.getMessage("modify");


        ss = sb.toString();

        ss = ss.replaceAll("\\$\\{i18n.getMessage\\('searchPlaceholder'\\)\\}", searchPlaceholder)
                .replaceAll("\\$\\{i18n.getMessage\\('new'\\)\\}", newStr)
                .replaceAll("\\$\\{i18n.getMessage\\('modify'\\)\\}", modify)
        ;

        if (!auto) {
            ss = ss.replaceAll("ctrolNode\\?index", "ctrolNode?index+500");
        }


        return ss;
    }

    /**
     * @return
     * @throws IOException
     */
    public static String getApiRequestNodeFile() throws IOException {
        String ss = fetchResourceByFilePath("/api-request-node.html.ftl");
        String[] lines = ss.split("\n");

        Integer[] ignoreArr = new Integer[]{
                3, 4, 5,
                6, 7, 8,
                15, 16, 17, 18, 19,
                57, 58, 59, 60, 61, 62, 63, 64, 65
        };
        Map<Integer, String> ignoreLine = genMapByArray(ignoreArr);

        StringBuilder sb = new StringBuilder();
        sb.append("<#list requestNodes as requestNode>\n<div class=\"action-item\">");

        for (int i = 0; i < lines.length; i++) {

            if (ignoreLine.containsKey(i + 1)) {
                continue;
            }

            sb.append(lines[i] + "\n");
        }

        sb.append("</div>\n<hr>\n</#list>\n");

        // replace
        ss = sb.toString();

        I18n i18n = new I18n();


        ss = ss.replaceAll("\\$\\{i18n.getMessage\\('deprecated'\\)\\}", i18n.getMessage("deprecated"))
                .replaceAll("\\$\\{i18n.getMessage\\('requestUrl'\\)\\}", i18n.getMessage("requestUrl"))
                .replaceAll("\\$\\{i18n.getMessage\\('requestParameters'\\)\\}", i18n.getMessage("requestParameters"))
                .replaceAll("\\$\\{i18n.getMessage\\('parameterName'\\)\\}", i18n.getMessage("parameterName"))
                .replaceAll("\\$\\{i18n.getMessage\\('parameterType'\\)\\}", i18n.getMessage("parameterType"))
                .replaceAll("\\$\\{i18n.getMessage\\('parameterNeed'\\)\\}", i18n.getMessage("parameterNeed"))
                .replaceAll("\\$\\{i18n.getMessage\\('description'\\)\\}", i18n.getMessage("description"))
                .replaceAll("i18n.getMessage\\('yes'\\)", "'" + i18n.getMessage("yes") + "'")
                .replaceAll("i18n.getMessage\\('no'\\)", "'" + i18n.getMessage("no") + "'")
                .replaceAll("\\$\\{i18n.getMessage\\('requestBody'\\)\\}", i18n.getMessage("requestBody"))
                .replaceAll("\\$\\{i18n.getMessage\\('responseResult'\\)\\}", i18n.getMessage("responseResult"))
        ;


        return ss;
    }

    public static String replaceContent(String res, String s, String e, String replaceStr) {
        int sI = res.indexOf(s) + s.length();
        int eI = res.indexOf(e);

        return res.substring(0, sI) + replaceStr + res.substring(eI);
    }

    public static void main(String[] args) throws IOException {

        String ss = null;
//        ss = getApiCommonCatalogFile();
//        ss = getApiIndexFile("自动生成文档工具");
//        ss = getApiControllerFile("自动生成文档工具", "用户管理接口");
//        ss = getApiRequestNodeFile();
        ss = getApiCommonCatalogFile(2, true);


//        ss = replaceContent(ss, "<!--catalog-auto-start-->", "<!--catalog-auto-end-->", "fdsafds");

        System.out.println(ss);

    }

}
